<!--  -->
<template>
	<div class="app-container" v-if="dialogVisible">
		<el-dialog  :title="typeText[type] +' ('+ eleTypeText[eleType] +')'" top="30px" :visible.sync="dialogVisible" width="800px" :before-close="handleClose">
			<div>
				<div style="margin-bottom: 15px;overflow-y: auto;max-height: 110px;">
					<el-tag :disable-transitions="true" v-for="(item, index) in tags" :key="item.id" :type="item.type == 'departmentName' ? 'warning' : ''" closable @close="changeeaTag(item)">
						<ww-open-data :type="item.type" :openid="item.id"></ww-open-data>
					</el-tag>
				</div>
				<el-select
					style="width: 100%;"
					v-model="value"
					filterable
					remote
					reserve-keyword
					placeholder="请输入搜索内容"
					:remote-method="remoteMethod"
					:loading="loading"
					@change="eleChange"
				>
					<el-option v-for="item in options" :key="item.id" :label="item.id" :value="item.id">
						<ww-open-data :type="item.type" :openid="item.id"></ww-open-data>
					</el-option>
				</el-select>
				<el-tabs style="margin-top: 20px;" v-model="activeName" @tab-click="handleClick">
					<el-tab-pane label="部门" name="department" v-if="type == 'all' || type == 'department'">
						<div class="department-view" >
							<div class="department-title" v-if="departmentListAll.length">
								<ww-open-data type="departmentName" :openid="departmentListAll[0].id"></ww-open-data>
							</div>
							<el-tree :data="departmentList" ref="tree" :show-checkbox="eleType == 'checkbox'" :expand-on-click-node="eleType == 'checkbox'" @node-click="departmentHandleNodeClick" node-key="id" @check-change="handleCheckChange" :default-expanded-keys="defaultExpandedKeys">
								<span class="custom-tree-node" slot-scope="{ node, data }">
									<div style="display: flex;align-items: center;">
										<img style="width: 15px;margin-right: 5px;" src="@/assets/image/bumen.png" />
										<!-- <span>{{ data.id }}</span> -->
										<ww-open-data type="departmentName" :openid="data.id"></ww-open-data>
									</div>
								</span>
							</el-tree>
						</div>
					</el-tab-pane>
					<el-tab-pane label="成员" name="user" v-if="type == 'all' || type == 'user'">
						<div class="user-view" v-if="isOpenUser">
							<div class="user-col-l">
								<el-tree :data="departmentListAll" @node-click="handleNodeClick"  :expand-on-click-node="false" node-key="id" :default-expanded-keys="defaultExpandedKeys">
									<span class="custom-tree-node" slot-scope="{ node, data }">
										<div style="display: flex;align-items: center;">
											<img style="width: 15px;margin-right: 5px;" src="@/assets/image/bumen.png" />
											<!-- <span>{{ data.id }}</span> -->
											<ww-open-data type="departmentName" :openid="data.id"></ww-open-data>
										</div>
									</span>
								</el-tree>
							</div>
							<div class="user-col-r">
								<el-table
									style="margin-left:10px;width: 100%;"
									max-height="450px"
									ref="table"
									:data="userData"
									tooltip-effect="dark"
									@select="handleSelectionChange"
									@select-all="handleSelectionChangeAll"
								>
									<el-table-column label="全选">
										<template slot-scope="scope">
											<div style="display: flex;align-items: center;">
												<img style="width: 30px;margin-right: 5px;" :src="scope.row.avatar" />
												<ww-open-data type="userName" :openid="scope.row.userid"></ww-open-data>
											</div>
										</template>
									</el-table-column>
									<el-table-column v-if="eleType == 'checkbox'" key="selection" type="selection" width="55" align="right"></el-table-column>
									<el-table-column v-if="eleType == 'radio'" key="ele" label="操作" width="80"  align="right">
										<template slot-scope="scope" >
											<el-button size="mini" @click="radioUser(scope.row)">选择</el-button>
										</template>
									</el-table-column>
								</el-table>
							</div>
						</div>
					</el-tab-pane>
				</el-tabs>
			</div>
			<div class="dialog-footer">
				<div class="yx-text">已选 {{tags.length}}</div>
				<div>
					<el-button @click="onReset()">重置已选</el-button>
					<el-button type="primary" @click="onSubmit()">确 定</el-button>
				</div>
			</div>
		</el-dialog>
		<!-- <ww-open-data v-for="(item, index) in list" :key="index" :type="item.type" :openid="item.openid"></ww-open-data> -->
	</div>
</template>

<script>
import wwOpenData from './txl.vue';
import Api from '@/api/pages/qywx/index.js';
export default {
	name: 'qywx',
	props:{
	
	},
	components: { wwOpenData },
	data() {
		return {
			dialogVisible: false,
			activeName: 'department',
			userIndex: 0,
			input: '',
			checkList: [],
			userData: [],
			type:'all',//all 、department 、user
			eleType:'checkbox', //radio ，checkbox
			typeText:{
				'all':'选择部门、成员',
				'user':'选择成员',
				'department':'选择部门',
			},
			eleTypeText:{
				'radio':'单选',
				'checkbox':'多选',
			},
			queryType:{
				'all':0,
				'user':1,
				'department':2,
			},
			// list: [
			// 	{
			// 		type: 'departmentName', //用户id  userName ；部门id  departmentName
			// 		openid: 1
			// 	}
			// ],
			options: [],
			value: [],
			list: [],
			loading: false,
			states: ['Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'],
			department:[],//数组结构
			departmentList: [],
			departmentListAll:[],
			tags: [],
			departmentTags:[],
			userTags:[],
			defaultExpandedKeys:[],
			isOpenUser:false,
		};
	},
	mounted() {
		// this.addJs('//res.wx.qq.com/open/js/jweixin-1.2.0.js');
		// this.addJs('//open.work.weixin.qq.com/wwopen/js/jwxwork-1.0.0.js');
		// this.addJs('https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js');
		// this.init();
		// this.getData();
		this.list = this.states.map(item => {
			return { value: `value:${item}`, label: `label:${item}` };
		});
		console.log('userInfo',this.userInfo)
	},
	computed: {
	  userInfo() {
	  	return this.$store.state.getInfo
	  },
	},
	methods: {
		// 单选部门
		departmentHandleNodeClick(item) {
			if(this.eleType == 'radio') {
				this.tags = [
					{
						id:item.id,
						type:'departmentName'
					}
				];
			}
		},
		//选择部门
		handleCheckChange() {
			let arr = this.$refs.tree.getCheckedNodes();
			let tags = [];
			arr.forEach(item => {
				tags.push({
					id:item.id,
					type:'departmentName'
				});
			})
			this.departmentTags = tags;
			this.tags = [...this.departmentTags,...this.userTags];
		},
		// 勾选成员
		handleSelectionChange(e,row) {
			let tags = [];
			e.forEach(item => {
				tags.push({
					id:item.userid,
					type:'userName'
				});
			})
			this.userTags = tags;
			this.tags = [...this.departmentTags,...this.userTags];
		},
		radioUser(row){
			this.tags = [{id:row.userid,type:'userName'}]
		},
		// 全选成员
		handleSelectionChangeAll(e) {
			if(e.length) {
				e.forEach(row => {
					this.handleSelectionChange(e,row)
				})
			}else{
				this.userData.forEach(row => {
					this.handleSelectionChange([],row)
				})
			}
		},
		// 点击部门
		handleNodeClick(e) {
			this.getUser(e.id,1);
		},
		// 删除标签
		changeeaTag(tag) {
			// console.log(tag);
			this.tags.splice(this.tags.indexOf(tag), 1);
			if (tag.type == 'departmentName') {
				this.$refs.tree.setChecked(tag.id,false);
			}else{
				let row = this.userData.find(item => item.userid == tag.id)
				this.$refs.table.toggleRowSelection(row,false);
			}
		},
		// 重置已选
		onReset() {
			this.tags.forEach(tag => {
				if (tag.type == 'departmentName') {
					this.$refs.tree.setChecked(tag.id,false);
				}else{
					let row = this.userData.find(item => item.userid == tag.id)
					if(row) {
						this.$refs.table.toggleRowSelection(row,false);
					}
				}
			})
			this.departmentTags = [];
			this.userTags = [];
			this.tags = [];
		},
		// 导入选择状态
		toggleRowSelection() {
			let userAll = this.tags.filter(item => item.type == 'userName')
			userAll.forEach(item => {
				let row = this.userData.find(user => user.userid == item.id)
				// console.log('row',row)
				if(row) {
					this.$refs.table.toggleRowSelection(row,true);
				}
			})
		},
		remoteMethod(query) {
			if (query !== '') {
				this.loading = true;
				this.search(query);
				// setTimeout(() => {
				// 	this.loading = false;
				// 	this.options = this.list.filter(item => {
				// 		return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
				// 	});
				// }, 200);
			} else {
				this.options = [];
			}
		},
		// 获取部门
		getData(state = false) {
			Api.department_list().then(res => {
				if (res.state) {
					this.department = res.data;
					this.departmentListAll = this.handleTree(res.data);
					let index = this.departmentListAll.findIndex(item => item.parentid == 0);
					this.departmentList = this.departmentListAll[index].children;
					this.departmentList.forEach(item => {
						this.defaultExpandedKeys.push(item.id);
					})
					if(state) {
						this.getUser(this.departmentListAll[0].id, 1);
					}
				} else {
					this.$message(res.msg);
				}
			});
		},
		// 获取成员
		getUser(id, type) {
			Api.department_user_list({
				department_id: id,
				fetch_child: type //1/0：是否递归获取子部门下面的成员
			}).then(res => {
				if (res.state) {
					this.userData = res.data;
					setTimeout(() => {
						this.toggleRowSelection();
					},500)
				} else {
					this.$message(res.msg);
				}
			});
		},
		// 搜索
		search(word) {
			let data = {
				query_word:word,//搜索关键词。当查询用户时应为用户名称、名称拼音或者英文名；当查询部门时应为部门名称或者部门名称拼音
				query_type:this.queryType[this.type],//查询类型 1：查询用户，返回用户userid列表 2：查询部门，返回部门id列表。 不填该字段或者填0代表同时查询部门跟用户
				offset:'',//查询的偏移量，每次调用的offset在上一次offset基础上加上limit
				limit:200,//查询返回的最大数量，默认为50，最多为200，查询返回的数量可能小于limit指定的值
				full_match_field:'',//精确匹配的字段。1：匹配用户名称或者部门名称 2：匹配用户英文名。不填则为模糊匹配
			}
			Api.search(data).then(res => {
				if (res.state) {
					this.loading = false;
					let userIds = res.data.query_result.user ? res.data.query_result.user.userid : [];
					let partyIds = res.data.query_result.party ? res.data.query_result.party.department_id : [];
					let users = [];
					let partys = []
					userIds.forEach(item => {
						users.push({
							id:item,
							type:'userName'
						})
					})
					partyIds.forEach(item => {
						partys.push({
							id:item,
							type:'departmentName'
						})
					})
					this.options = [...partys,...users]
				} else {
					this.$message(res.msg);
				}
			});
		},
		// 处理树形结构
		handleTree(arr) {
			let cloneData = JSON.parse(JSON.stringify(arr)); // 对源数据深度克隆
			return cloneData.filter(father => {
				let branchArr = cloneData.filter(child => father.id == child.parentid); //返回每一项的子级数组
				branchArr.length > 0 ? (father.children = branchArr) : ''; //如果存在子级，则给父级添加一个children属性，并赋值
				return father.parentid == 0; //返回第一层
			});
		},
		// 打开窗口
		open(type = 'all',eleType = 'checkbox') {
			this.type = type;
			this.eleType = eleType;
			this.dialogVisible = true;
			if(type == 'user') {
				this.activeName = 'user';
				this.isOpenUser = true;
				if (this.userData.length == 0) {
					this.getData(true);
				}
			}else{
				this.activeName = 'department';
				this.getData();
			}
		},
		handleClose() {
			this.dialogVisible = false;
			this.isOpenUser = false;
			this.options = [];
			this.userData = [];
			this.department = [];
			this.departmentList = [];
			this.departmentListAll = [];
			this.onReset();
		},
		// 切换nav
		handleClick() {
			if(this.activeName = 'user') {
				this.isOpenUser = true
				if (this.userData.length == 0) {
					this.getUser(this.departmentListAll[0].id, 1);
				}
			}
		},
		// 搜索选择
		eleChange(e){
			// console.log(e)
			let index = this.department.findIndex(item => item.id == e)
			if(this.tags.find(item => item.id == e)) {
				this.value = ''
				return
			}
			// 单选多选
			if(this.eleType == 'radio') {
				if(index == '-1') {
					this.userTags = [];
					this.tags = [{id:e,type:'userName'}];
					let row = this.userData.find(user => user.userid == e);
					if(row) {
						this.$refs.table.toggleRowSelection(row,true);
					}
				}else{
					this.departmentTags = [];
					this.tags = [{id:e,type:'departmentName'}];
				}
			}else{
				if(index == '-1') {
					this.userTags.push({id:e,type:'userName'});
					this.tags.push({id:e,type:'userName'});
					let row = this.userData.find(user => user.userid == e);
					if(row) {
						this.$refs.table.toggleRowSelection(row,true);
					}
				}else{
					this.$refs.tree.setChecked(e,true);
				}
			}
			this.value = ''
		},
		// 提交
		onSubmit() {
			let ids = [];
			this.tags.forEach(item => {
				ids.push(item.id)
			})
			if(!ids.length) {
				this.$message({
				  message: '请'+this.typeText[this.type],
				  type: 'warning'
				});
				return;
			}
			this.$emit('submit',this.eleType == 'radio' ? ids[0] :  ids );
			this.handleClose();
		},
		init() {
			(async () => {
				try {
					console.info('WWOpenData demo start');
					if (/MicroMessenger/i.test(navigator.userAgent)) {
						await config(window.configParams);
					}
					let res = await getAgentConfigParams();
					let agentConfigParams = {
						corpid: res.data.appId, // 必填，企业微信的corpid，必须与当前登录的企业一致
						agentid: 1000082, // 必填，企业微信的应用id （e.g. 1000247）
						timestamp: res.data.timestamp, // 必填，生成签名的时间戳
						nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
						signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
						jsApiList: ['selectExternalContact'] //必填，传入需要使用的接口名称
					};
					await agentConfig(agentConfigParams);
					// 若一切正常，此时可以在 window 上看到 WWOpenData 对象
					console.info('window.WWOpenData', window.WWOpenData);
					if (WWOpenData.checkSession) {
						WWOpenData.checkSession({
							success() {
								console.info('open-data 登录态校验成功');
							},
							fail() {
								console.error('open-data 登录态过期');
							}
						});
					}
					if (WWOpenData.on) {
						/**
						 * ww-open-data 元素数据发生变更时触发
						 */
						WWOpenData.on('update', event => {
							const openid = event.detail.element.getAttribute('openid');
							console.info('渲染数据发生变更', openid, event.detail.hasData);
						});
						/**
						 * ww-open-data 获取数据失败时触发
						 */
						WWOpenData.on('error', () => {
							console.error('获取数据失败');
						});
					}
					/**
					 * 创建 ww-open-data 元素
					 */
					// const container = document.getElementById('container')
					// // 这里的 window.openidList 是该 demo 页面自行组织的数据，不具备普遍性
					// // 开发者进行开发时，需要自己拿到授权企业相对应的 openid
					// // 关于 openid 的定义与获得方式，可以关注文档注意事项的第 5 点
					// for (const openid of window.openidList) {
					// 	const element = document.createElement('ww-open-data')
					// 	element.setAttribute('type', 'departmentName')
					// 	element.setAttribute('openid', openid)
					// 	container.appendChild(element)
					// }
					// /**
					//  * 绑定 document 上全部的 ww-open-data 元素
					//  */
					// WWOpenData.bindAll(document.querySelectorAll('ww-open-data'))
					console.info('WWOpenData demo end');
				} catch (error) {
					console.error('WWOpenData demo error', error);
				}
				/**
				 * 调用 wx.config
				 *
				 * @see https://open.work.weixin.qq.com/api/doc/90001/90144/90547
				 */
				async function config(config) {
					return new Promise((resolve, reject) => {
						console.info('wx.config', config);
						wx.config(config);
						wx.ready(resolve);
						wx.error(reject);
					}).then(
						() => {
							console.info('wx.ready');
						},
						error => {
							console.error('wx.error', error);
							throw error;
						}
					);
				}
				/**
				 * 调用 wx.agentConfig
				 *
				 * @see https://open.work.weixin.qq.com/api/doc/90001/90144/90548
				 */
				async function agentConfig(config) {
					return new Promise((success, fail) => {
						console.info('wx.agentConfig', config);
						wx.agentConfig({
							...config,
							success,
							fail
						});
					}).then(
						res => {
							console.info('wx.agentConfig success', res);
							return res;
						},
						error => {
							console.error('wx.agentConfig fail', error);
							throw error;
						}
					);
				}
				async function getAgentConfigParams() {
					return new Promise((success, fail) => {
						Api.getSignData({wuye_id:''}).then(res => {
							if (res.state) {
								success(res);
							} else {
								fail(res);
							}
						})
						// $.ajax({
						// 	type: 'get',
						// 	url: 'http://wuye.frp.shandian001.com/wuye/qywx/jssdk/getSignData',
						// 	success: function(res) {
						// 		success(res);
						// 	},
						// 	error: function(err) {
						// 		fail(err);
						// 	}
						// });
					}).then(
						res => {
							console.info('wx.agentConfig success', res);
							return res;
						},
						error => {
							console.error('wx.agentConfig fail', error);
							throw error;
						}
					);
				}
			})();
		},
		addJs(src) {
			// 创建script标签，引入外部文件
			let script = document.createElement('script');

			script.type = 'text/javascript';
			script.src = src;

			document.getElementsByTagName('head')[0].appendChild(script);

			// 引入成功
			script.onload = function() {
				console.log('js资源已加载成功了');
			};
			// 引入失败
			script.onerror = function() {
				console.log('js资源加载失败了');
			};
		}
	}
};
</script>
<style lang="scss" scoped>
.department-title {
	font-size: 16px;
	margin-bottom: 10px;
}
.department-view {
	height: 450px;
	.list {
		height: 400px;
		overflow-y: auto;
	}
}
.user-view {
	height: 450px;
	display: flex;
	justify-content: space-between;
	.department-title {
		cursor: pointer;
	}
	.user-col-l {
		width: 50%;
		height: 100%;
		border-right: 2px solid #dfe4ed;
		.list {
			height: 400px;
			overflow-y: auto;
			.row {
				cursor: pointer;
				width: 100%;
				padding: 5px;
				.icon {
					color: #ff9600;
					margin-right: 5px;
				}
			}
			.row-bg {
				background: #f7f7f7;
			}
		}
	}
	.user-col-r {
		width: 50%;
	}
}
.checkbox {
	width: 80%;
	margin-bottom: 10px;
}
.dialog-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 10px;
	border-top: 2px solid #dfe4ed;
	.yx-text {
		color: #bbb;
	}
}
</style>

<style lang="scss">
.el-tag + .el-tag {
	margin-left: 10px;
	margin-bottom: 10px;
}
</style>
